/**
 * @author:linjiye
 * @date:2025/1/5
 * @desc:
 **/

import {StyleSheet, Text, TouchableOpacity, View, Image} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcTextInput from "@/components/FcTextInput";
import KeywordHighlighter from "@/components/KeywordHighlighter";
import NoData from "@/components/NoData";
import FcButton from "@/components/FcButton";
import {router, useLocalSearchParams} from "expo-router";
import FcModal from "@/components/FcModal";
import FormTitle from "@/components/FormTitle";
import {Flex, Toast} from "@ant-design/react-native";
import {
    useAddGroupMutation, useBatchGroupMutation,
    useDeleteProductMutation,
    useEditProductMutation,
    useGetItemListQuery, useGetParentListQuery
} from "@/store/api/aiOriginality/aiOriginalityApi";
import FcSearch from "@/components/FcSearch";

type Props = {}

const editProductName = (props: Props) => {
    const [searchText, setSearchText] = useState('')
    const [list, setList] = useState([])
    const [currentItem, setCurrentItem] = useState({})
    const [selectData, setSelectData] = useState([])
    const [isDelete, setIsDelete] = useState(false)
    const [isEdit, setIsEdit] = useState(false)
    const [typeList, setTypeList] = useState([
        {
            name: '提供产品',
            id: 1,
        }
    ])
    const [typeId, setTypeId] = useState<any>(null)
    const [isMove, setIsMove] = useState(false)
    const [moveList, setMoveList] = useState([])
    const [moveItem, setMoveItem] = useState({})
    const [isAdd,setIsAdd] = useState(false)
    const [typeList1, setTypeList1] = useState([
        {
            name: '提供产品',
            id: 1,
        },{
            name: '提供服务',
            id: 2,
        },{
            name: '经营场景',
            id: 3,
        }
    ])
    const [typeId1, setTypeId1] = useState(typeList[0]?.id)
    const [groupName, setGroupName] = useState('')


    const {data:productResData,isSuccess:productSuccess, refetch:productRefetch}= useGetItemListQuery?.({
        parentId: '',
        name: searchText,
        types: typeId
    })
    const [deleteProductFun] = useDeleteProductMutation()
    const [editProductFun] = useEditProductMutation()
    const {data:groupResData,isSuccess:groupSuccess, refetch:groupRefetch}= useGetParentListQuery?.({
        types: '',
        name: ''
    })
    const [addGroupFun] = useAddGroupMutation()
    const [batchGroupFun] = useBatchGroupMutation()

    const {categoryId} = useLocalSearchParams()

    useEffect(() => {
        setTypeId(categoryId)

        if (productResData) {
            let list = productResData?.result || []
            const gArr = []
            list.forEach((item) => {
                gArr.push({
                    title: item.groupName,
                    isSelected: false,
                    ...item
                })
            })
            setList(gArr)
        }

        if (groupResData) {
            let list = groupResData?.result || []
            setMoveList(list)
        }
    },[productSuccess,productResData,groupSuccess,groupResData, categoryId])

    const handleSelectItem = (item, index) => {
        let newList = [],newSelectData = []
        newList = [...list]
        newList[index].isSelected = !newList[index].isSelected
        newSelectData = newList?.filter(item => item.isSelected)
        setList(newList)
        setSelectData(newSelectData)
    }

    const handleComplete = () => {
        router.back()
    }

    const handleDelete = () => {
        setIsDelete(true)
    }

    const handleType = (val) => {
        setTypeId(val.id)
    }

    const handleEdit = (val) => {
        setCurrentItem(val)
        setIsEdit(true)
    }

    function takeDelete() {
        deleteProductFun({
            ids: selectData?.map(item => item.id)
        }).then(res => {
            if (res?.data?.code === 200) {
                Toast.info('删除成功')
                setIsDelete(false)
                setSelectData([])
                // productRefetch()
            }
        })
    }

    function takeEdit() {
        editProductFun({
            id: currentItem?.id,
            name: currentItem.name,
            parentId: currentItem.parentId,
        }).then(res => {
            if (res?.data?.code === 200) {
                Toast.info('修改成功')
                setIsEdit(false)
                setCurrentItem({})
                // productRefetch()
            }
        })
    }

    function addGroupName() {
        if (!groupName) {
            Toast.info('请输入分组名称')
            return
        }

        addGroupFun({
            name: groupName,
            type: typeId,
            parentId: 0,
        }).then(res => {
            if (res?.data?.code === 200) {
                setIsAdd(false)
                setGroupName('')
                Toast.info('新增成功')
            }
        })
    }

    function takeMove() {
        batchGroupFun({
            idList: selectData?.map(item => item.id),
            parentId: moveItem?.id
        }).then(res => {
            if (res?.data?.code === 200) {
                Toast.info('移动成功')
                setIsMove(false)
                setSelectData([])
                setMoveItem({})
                // productRefetch()
            }
        })
    }

    return (
        <PageScrollView
            pageTab={
                <PageTabBar
                    style={{marginVertical: 10}}
                    title={'产品名称'}
                    right={
                        <TouchableOpacity style={{flexDirection: 'row'}} onPress={() => handleComplete()}>
                            <FcButton
                                type='BjJB'
                                colors={['#6989FF', '#C65EFD']}
                                style={{width: 48, height: 28, justifyContent: 'center'}}
                                itemStyle={{borderRadius: 8, fontSize: 12}}
                                textName='完成'/>
                        </TouchableOpacity>

                    }
                />
            }
            pageHeader={
                <FcSearch searchText={searchText} onSearch={(val) => setSearchText(val)}/>
            }
            pageBottom={
                <View style={styles.page_bottom}>
                    <Text style={styles.delete_num}>已选 {selectData?.length} 个</Text>
                    <View style={styles.delete_btn_wrap}>
                        <TouchableOpacity style={[styles.delete_btn, {marginRight: 23}]}
                                          onPress={() => setIsMove(true)}>
                            <Text style={{
                                fontFamily: 'FcIconFont',
                                fontSize: 20,
                                color: selectData?.length > 0 ? 'rgba(0, 0, 0, 0.9)' : 'rgba(0, 0, 0,.3)'
                            }}>&#xe631;</Text>
                            <Text
                                style={[styles.delete_text, {color: selectData?.length > 0 ? 'rgba(0, 0, 0, 0.9)' : 'rgba(0, 0, 0, 0.3)'}]}>移动</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.delete_btn} onPress={() => handleDelete()}>
                            <Text style={{
                                fontFamily: 'FcIconFont',
                                fontSize: 18,
                                color: selectData?.length > 0 ? 'rgba(250,81,81,1)' : 'rgba(250,81,81,.3)'
                            }}>&#xe61d;</Text>
                            <Text
                                style={[styles.delete_text, selectData?.length > 0 && styles.delete_active]}>删除</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            }
        >
            <View>
                <View style={styles.search_item_wrap}>
                    <KeywordHighlighter
                        text="全屋定制"
                        keywords=""
                        textStyle={styles.search_text}
                        textHeightLightStyle={{color: '#2856FF'}}
                    />
                </View>
                {list?.map((item, index) => (
                    <View style={styles.item_wrap} key={index}>
                        <View style={styles.item_left}>
                            <TouchableOpacity style={[styles.select_icon, item.isSelected && styles.select_active]}
                                              onPress={() => handleSelectItem(item, index)}>
                                {item.isSelected && <Text
                                    style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
                            </TouchableOpacity>
                            <KeywordHighlighter
                                text={item.name}
                                keywords={searchText}
                                textStyle={styles.search_text}
                                textHeightLightStyle={{color: '#2856FF'}}
                            />
                        </View>
                        <View style={styles.item_right}>
                            <TouchableOpacity onPress={() => handleEdit(item)}>
                                <Text style={{
                                    fontFamily: 'FcIconFont',
                                    fontSize: 20,
                                    color: 'rgba(0,0,0,0.5)'
                                }}>&#xe630;</Text>
                            </TouchableOpacity>
                            <TouchableOpacity>
                                <Text style={{
                                    fontFamily: 'FcIconFont',
                                    fontSize: 20,
                                    color: 'rgba(0,0,0,0.5)',
                                    marginLeft: 20
                                }}>&#xe633;</Text>
                            </TouchableOpacity>
                        </View>
                    </View>

                ))}
                {list?.length <= 0 &&
                    <View style={{
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        paddingTop: 60,
                        paddingBottom: 120
                    }}>
                        <NoData hintText='暂无产品'/>
                        {/*<FcButton*/}
                        {/*    onClick={() => setIsAdd(true)}*/}
                        {/*    type='BjJB'*/}
                        {/*    colors={['#6989FF', '#C65EFD']}*/}
                        {/*    style={{width: 74, height: 32, justifyContent: 'center'}}*/}
                        {/*    itemStyle={{borderRadius: 8}}*/}
                        {/*    textName='去新增'></FcButton>*/}
                    </View>
                }
            </View>
            <FcModal
                isOpen={isDelete}
                transparent
                closeShow={false}
                animationType='fade'
                onFcModalClose={() => setIsDelete(false)}
                style={styles.modal_default}
                titleText={'确认要删除吗？'}
                titleBottomBorderWidth={0}
                footer={[
                    {
                        text: '取消',
                        onPress: () => setIsDelete(false),
                        style: {color: 'rgba(0, 0, 0, 0.5)', fontSize: 17},
                    },
                    {
                        text: '确认',
                        onPress: () => takeDelete(),
                        style: {color: '#2856FF', fontSize: 17},
                    },
                ]}
            >
                <Text style={{textAlign: 'center', color: 'rgba(0,0,0,0.5)'}}>一旦删除，当前分组将被删除哦~</Text>
            </FcModal>
            <FcModal
                isOpen={isEdit}
                transparent
                closeShow={false}
                animationType='fade'
                onFcModalClose={() => setIsEdit(false)}
                style={styles.modal_default}
                titleText={'编辑产品'}
                titleBottomBorderWidth={0}
                footer={[
                    {
                        text: '取消',
                        onPress: () => setIsEdit(false),
                        style: {color: 'rgba(0, 0, 0, 0.5)', fontSize: 17},
                    },
                    {
                        text: '确认',
                        onPress: () => takeEdit(),
                        style: {color: '#2856FF', fontSize: 17},
                    },
                ]}
            >
                <View style={{paddingBottom: 20}}>
                    <FormTitle style={{paddingTop: 0}} isLeftIcon title='选择类目'/>
                    <Flex wrap='wrap' style={styles.type_menu}>
                        <FcButton
                            type='txtBK'
                            style={[styles.type_menu_item]}
                            itemStyle={{width: '100%', height: '100%'}}
                            textName={currentItem.type == 1 ? '提供产品' : (currentItem.type == 2 ? '提供服务' : '经营场景')} borderWidth={1}></FcButton>
                    </Flex>
                    <FcTextInput text={currentItem.name} placeholder={'请输入产品名称'}
                                 onChangeText={(val) => setCurrentItem({...currentItem,name:val})}
                                 height={56}/>
                </View>
            </FcModal>
            <FcModal
                isOpen={isMove}
                onFcModalClose={() => setIsMove(false)}
                titleText='移动至分组'
                bottom={
                    <View style={styles.move_bottom}>
                        <TouchableOpacity style={{flexDirection: 'row', alignItems: 'center'}} onPress={() => setIsAdd(true)} >
                            <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: 'rgba(0,0,0,0.9)'}}>&#xe63a;</Text>
                            <Text style={{fontSize: 15, color: '#2856FF',marginLeft: 4}}>新增分组</Text>
                        </TouchableOpacity>
                        <FcButton
                            onClick={() => takeMove()}
                            type='BjJB'
                            colors={moveItem.id?['#6989FF', '#C65EFD']:['rgba(105,137,255,0.4)','rgba(198,94,253,0.4)']}
                            style={{width: 88, height: 32, justifyContent: 'center'}}
                            itemStyle={{borderRadius: 8, fontSize: 15}}
                            textName='移动至此'/>
                    </View>
                }
            >
                {moveList?.map((item, index) => (
                    <View style={[styles.item_wrap, {marginHorizontal: 16}]} key={index}>
                        <View style={styles.item_left}>
                            <TouchableOpacity
                                style={[styles.select_icon, item.id === moveItem.id && styles.select_active]}
                                onPress={() => setMoveItem(item)}>
                                {item.id === moveItem.id && <Text
                                    style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
                            </TouchableOpacity>
                            <KeywordHighlighter
                                text={item.name}
                                keywords={searchText}
                                textStyle={styles.search_text}
                                textHeightLightStyle={{color: '#2856FF'}}
                            />
                            <Text>({item.count})</Text>
                        </View>
                    </View>

                ))}
            </FcModal>
            <FcModal
                isOpen={isAdd}
                transparent
                closeShow={false}
                animationType='fade'
                onFcModalClose={() => setIsAdd(false)}
                style={styles.modal_default}
                titleText={'新增分组'}
                titleBottomBorderWidth={0}
                footer={[
                    {
                        text: '取消',
                        onPress: () => setIsAdd(false),
                        style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
                    },
                    {
                        text: '确认',
                        onPress: () => addGroupName(),
                        style: { color: '#2856FF',fontSize: 17 },
                    },
                ]}
            >
                <View style={{paddingBottom: 20}}>
                    <FormTitle style={{paddingTop: 0}} isLeftIcon title='选择类目' />
                    <Flex wrap='wrap' style={styles.type_menu}>
                        {typeList1?.map((item, index) =>
                            <View key={index}>
                                <FcButton
                                    onClick={() => handleType(item)}
                                    type={typeId === item.id ? 'txtBK' : 'default'}
                                    style={[styles.type_menu_item]}
                                    itemStyle={{width: '100%', height: '100%'}}
                                    textName={item.name} borderWidth={1}></FcButton>
                            </View>
                        )}
                    </Flex>
                    <FcTextInput text={groupName} placeholder={'请输入分组名称'}
                                 onChangeText={setGroupName}
                                 height={56}/>
                </View>
            </FcModal>
        </PageScrollView>
    )
}


export default editProductName

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white',
        borderRadius: 8,
        paddingHorizontal: 16,
    },
    tabBar_btn: {
        width: 64,
        height: 28,
        display: 'flex',
        justifyContent: "center",
        alignItems: "center",
        fontSize: 12,
        color: '#2856FF',
        borderRadius: 8,
        backgroundColor: 'white'
    },
    search_item_wrap: {
        flexDirection: 'row',
        minHeight: 56,
        display: 'flex',
        alignItems: "center",
        borderBottomWidth: 1,
        borderBottomColor: 'rgba(0,0,0,0.1)',
    },
    search_text: {
        color: 'rgba(0, 0, 0, 0.9)'
    },
    item_wrap: {
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "space-between",
        minHeight: 56,
        display: 'flex',
        borderBottomWidth: 1,
        borderBottomColor: 'rgba(0,0,0,0.1)',
    },
    item_left: {
        flexDirection: 'row',
        alignItems: "center"
    },
    select_icon: {
        width: 20,
        height: 20,
        borderRadius: '50%',
        borderWidth: 1,
        borderColor: 'rgba(0,0,0,0.5)',
        marginRight: 12,
    },
    select_active: {
        borderColor: '#2856FF',
        backgroundColor: '#2856FF',
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "center"
    },
    item_right: {
        flexDirection: 'row',
        alignItems: "center"
    },
    page_bottom: {
        backgroundColor: 'white',
        height: 48,
        paddingHorizontal: 16,
        position: "relative",
    },
    delete_num: {
        lineHeight: 48,
        fontSize: 12,
        color: 'rgba(0,0,0,0.3)'
    },
    delete_btn_wrap: {
        position: "absolute",
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        alignItems: "center",
        justifyContent: "center",
        flexDirection: "row"
    },
    delete_btn: {
        alignItems: "center",
        justifyContent: "center",
        flexDirection: "row"
    },
    delete_text: {
        fontSize: 14,
        color: 'rgba(250,81,81,0.3)'
    },
    delete_active: {
        color: 'rgba(250,81,81,1)'
    },
    modal_default: {
        width: 280,
        borderBottomRightRadius: 12,
        borderBottomLeftRadius: 12,
    },

    type_menu: {
        display: "flex",
        flexWrap: "wrap",
        flexDirection: "row",
        marginLeft: -3,
        marginBottom: 16
    },
    type_menu_item: {
        width: 78,
        height: 40,
        lineHeight: 40,
        borderRadius: 8,
        marginHorizontal: 3,
        marginBottom: 6
    },
    move_bottom: {
        backgroundColor: 'white',
        height: 48,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: 16
    }
})